﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Tisonet.Dobrak.Domain.Models;

namespace Tisonet.Dobrak.Client.WP8.Services
{
    public class MoviesService : IMoviesService
    {
        private readonly Uri _serverUri;

        public MoviesService(Uri serverUri)
        {
            _serverUri = serverUri;
        }

        public void DownloadsMovieAsync(string movieName, Action<Movie> onDownloaded)
        {
            var webClient = new WebClient();
           
            webClient.OpenReadCompleted += (sender, args) => DataDownloaded(args, onDownloaded, movieName);
            webClient.OpenReadAsync(CreateRequestUri(movieName));
        }

        private Uri CreateRequestUri(string movieName)
        {
            return new Uri(string.Format("{0}/{1}", _serverUri, movieName));
        }

        private void DataDownloaded(OpenReadCompletedEventArgs e, Action<Movie> onDownloaded, string movieName)
        {
            if (!e.Cancelled && e.Error == null)
            {
                using (var streamReader = new StreamReader(e.Result))
                {
                    using (var jsonReader = new JsonTextReader(streamReader))
                    {
                        var serializer = new JsonSerializer();
                        var movie = serializer.Deserialize<Movie>(jsonReader);
                        movie.Name = movie.Name ?? movieName;

                        if (onDownloaded != null)
                        {
                            onDownloaded(movie);
                        }
                    }
                }
            }
        }
    }
}
